﻿using Newtonsoft.Json;
using System;

namespace DotNet5.Mvc.Common
{
    /// <summary>
    /// Json帮助类
    /// </summary>
    public static class JsonHelper
    {
        /// <summary>
        /// 对象转JSON
        /// </summary>
        /// <param name="obj">对象</param>
        /// <param name="dateFormat">日期格式</param>
        /// <returns>JSON格式的字符串</returns>
        public static string ObjectToJSON(object obj, string dateFormat = "yyyy-MM-dd HH:mm")
        {
            string result = string.Empty;
            try
            {
                var jsonSerializerSettings = new JsonSerializerSettings();
                // 将属性名的首字母改为小写
                //jsonSerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                // 格式化日期格式
                jsonSerializerSettings.DateFormatString = dateFormat;
                result = JsonConvert.SerializeObject(obj, Formatting.None, jsonSerializerSettings);
            }
            catch (Exception ex)
            {
                result = string.Empty;
                ex.GetBaseException();
            }
            return result;
        }

        /// <summary>
        /// Json转换成对象
        /// </summary>
        /// <typeparam name="T">对象</typeparam>
        /// <param name="sJson">json</param>
        /// <returns>对象泛型集合</returns>
        public static T JsonToObject<T>(string sJson)
        {
            try
            {
                return JsonConvert.DeserializeObject<T>(sJson);
            }
            catch (Exception ex)
            {
                ex.GetBaseException();
                return default(T);
            }
        }
    }
}
